<template>
  <div class="content">
    <Form ref="formValidate" :model="form" :label-width="80">
      <div class="formBox" style="margin-bottom: 20px">
        <div class="formBox-item">
          <FormItem label="食材名称" prop="materialName">
            <Input v-model="form.materialName" maxlength="20" clearable placeholder="请输入食材名称" style="width: 200px">
            </Input>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="食材种类" prop="foodClass">
            <Select v-model="form.foodClass" style="width: 200px" placeholder="请选择食材种类" clearable>
              <Option :value="item.name" v-for="(item, index) in materialTypeList" :key="index">{{ item.name }}</Option>
            </Select>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="常用状态" prop="materialStatus">
            <Select v-model="form.materialStatus" style="width: 200px" placeholder="请选择常用状态" clearable>
              <Option value="-1">全部</Option>
              <Option value="0">不常用</Option>
              <Option value="1">常用</Option>
            </Select>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="新增食材" prop="isSystemFood	">
            <Select v-model="form.isSystemFood" style="width: 200px" placeholder="请选择新增食材" clearable>
              <Option value="-1">全部</Option>
              <Option value="0">否</Option>
              <Option value="1">是</Option>
            </Select>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="营养匹配" prop="foodNutritionalStatus">
            <Select v-model="form.foodNutritionalStatus" style="width: 200px" placeholder="请选择营养匹配" clearable>
              <Option value="-1">全部</Option>
              <Option value="0">未匹配</Option>
              <Option value="1">匹配</Option>
            </Select>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="产地" prop="province">
            <Select v-model="form.province" style="width: 200px" placeholder="请选择产地" clearable>
              <Option value="北京">北京</Option>
              <Option value="上海">上海</Option>
              <Option value="天津">天津</Option>
              <Option value="重庆">重庆</Option>
              <Option value="河北">河北</Option>
              <Option value="山西">山西</Option>
              <Option value="内蒙古">内蒙古</Option>
              <Option value="辽宁">辽宁</Option>
              <Option value="吉林">吉林</Option>
              <Option value="黑龙江">黑龙江</Option>
              <Option value="江苏">江苏</Option>
              <Option value="浙江">浙江</Option>
              <Option value="安徽">安徽</Option>
              <Option value="福建">福建</Option>
              <Option value="江西">江西</Option>
              <Option value="山东">山东</Option>
              <Option value="河南">河南</Option>
              <Option value="湖北">湖北</Option>
              <Option value="湖南">湖南</Option>
              <Option value="广东">广东</Option>
              <Option value="广西">广西</Option>
              <Option value="海南">海南</Option>
              <Option value="四川">四川</Option>
              <Option value="贵州">贵州</Option>
              <Option value="云南">云南</Option>
              <Option value="西藏">西藏</Option>
              <Option value="陕西">陕西</Option>
              <Option value="甘肃">甘肃</Option>
              <Option value="宁夏">宁夏</Option>
              <Option value="青海">青海</Option>
              <Option value="新疆">新疆</Option>
              <Option value="香港">香港</Option>
              <Option value="澳门">澳门</Option>
              <Option value="台湾">台湾</Option>
            </Select>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="季节" prop="month">
            <Select v-model="form.month" style="min-width: 200px;line-height: 32px;!important" placeholder="请选择季节"
              clearable multiple>
              <Option value="春季">春季</Option>
              <Option value="夏季">夏季</Option>
              <Option value="秋季">秋季</Option>
              <Option value="冬季">冬季</Option>
            </Select>
          </FormItem>
        </div>
        <cusButton  class="mr_20" type="primary" @onClick=" pages.page = 1; onInit();">查询</cusButton>
        <cusButton  class="mr_20" type="primary" @onClick="reset()">重置</cusButton>
      </div>
    </Form>
    <div class="content-bottom">
      <div class="btnBox">
        <div>
          <cusButton size="small" class="mr_20" type="primary" @onClick="syncOrganLocalFoodApi" :disabled="disabledCount">同步
          </cusButton>
          <span style="font-size: 16px;line-height: 35px">{{
            `倒计时${countDown}后可再次同步`
          }}</span>
        </div>
        <!-- <cusButton class="mr_20" type="primary" @onClick="onAdd()" ghost
          >添加</cusButton
        > -->
        <div>
          <!-- <cusButton class="mr_20" type="primary" @onClick="onBind()"
            >食谱原料绑定商品</cusButton
          > -->
          <cusButton size="small" type="primary" @onClick="onExport()">导出</cusButton>
        </div>
        <!-- <cusButton class="mr_20" type="primary" @onClick="onImport(1)"
          >导入食材</cusButton
        >
        <cusButton class="mr_20" type="primary" @onClick="onImport(2)"
          >导入副食筹措原料</cusButton
        >
        <cusButton class="mr_20" type="primary" @onClick="onImport(3)"
          >导入食材别名</cusButton
        > -->
      </div>
      <div class="tableBox">
        <cus-table border :loading="loading" :columns="columns" :data="data" :bottomClass="['cus-page']">
          <template slot-scope="{ row }" slot="materialStatus">
            {{ row.materialStatus === 1 ? "是" : "否" }}
            <i-switch :true-value="1" :false-value="0" v-model="row.materialStatus" @on-change="ifSwitchChange(row)">
            </i-switch>
          </template>
          <template slot-scope="{ row }" slot="isSystemFood">
            <div>{{ row.isSystemFood == 0 ? "否" : "是" }}</div>
          </template>
          <template slot-scope="{ row }" slot="foodNutritionalStatus">
            <div>{{ row.foodNutritionalStatus == 0 ? "未匹配" : "匹配" }}</div>
          </template>
          <template slot-scope="{ row }" slot="weightFlag">
            <div>{{ row.weightFlag == 0 ? "否" : "是" }}</div>
          </template>
          <template slot-scope="{ row }" slot="operation">
            <div class="flex">
              <cus-button type="text" size="small" :style="{ color: 'green', padding: '0 8px' }" @onClick="onDetail(row)">
                营养详情
              </cus-button>
              <cus-button type="text" size="small" :style="{ color: '#1E6FFF', padding: '0 8px' }" @onClick="onEdit(row)">
                查看
              </cus-button>
              <cus-button type="text" size="small" :style="{ color: 'orange', padding: '0 8px' }" @onClick="onPipei(row)">
                营养匹配
              </cus-button>
            </div>
            <!-- <div class="flex" style="justify-content: start;">
              <cus-button type="text" size="small" :style="{ color: 'orange', padding: '0 8px' }" @onClick="onPipei(row)">
                营养匹配
              </cus-button>
            </div> -->
          </template>
        </cus-table>
        <div style="width: 100%; display: flex; justify-content: flex-end">
          <cus-page :data="pages" @pageChange="onInit()"></cus-page>
        </div>
      </div>
    </div>
    <!-- 导入 -->
    <cus-uploadModal ref="cusUploadNutritionTagModal" :temp-src="exportNutritionTagTemp" :uploadFnc="uploadNutritionTag"
      :titleName="importName"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" @onOk="onInit"
      @onError="onError" :showTemp="showTemp"></cus-uploadModal>
    <!-- 添加、编辑  食材 -->
    <addFoodModal ref="addFoodModal"></addFoodModal>
    <!-- 为食谱原料绑定主副食商品名称 -->
    <bindFoodModal ref="bindFoodModal"></bindFoodModal>
    <!-- 营养详情 -->
    <nutritionalDetails ref="nutritionalDetails"></nutritionalDetails>
    <!-- 营养匹配 -->
    <nutritionalMatching ref="nutritionalMatching"></nutritionalMatching>
  </div>
</template>

<script>
import {
  localFoodSearch,
  materialType,
  localFoodDelete,
  downloadLocalFoodExcelTemplate,
  downloadFoodAliasExcel,
  inportLocalFoodVoExcel,
  inportFoodAliasExcel,
  exportLocalFoodVoExcel,
  inportRaiseFoodExcel,
  postBasicUpdateLocalFoodIsCommonly
} from "@/api/business/dishesModule";
import { syncOrganLocalFood } from "@/api/business/business";
import { runInThisContext } from "vm";
import addFoodModal from "./components/addFoodModal.vue";
import bindFoodModal from "./components/bindFoodModal.vue";
import nutritionalDetails from "./components/nutritionalDetails.vue";
import nutritionalMatching from "./components/nutritionalMatching.vue";

export default {
  components: {
    addFoodModal,
    bindFoodModal,
    nutritionalDetails,
    nutritionalMatching
  },
  data() {
    return {
      ruleValidate: {},
      form: {
        materialName: "", // 食材名称
        month: [], // 季节
        foodClass: "", // 食材种类
        province: "", // 产地
        materialStatus: "-1", // 常用状态
        isSystemFood: "-1", // 新增食材
        foodNutritionalStatus: "-1" // 营养匹配
      },
      materialTypeList: [], // 食材种类列表
      exportNutritionTagTemp: "", // 下载模板地址
      uploadNutritionTag: inportLocalFoodVoExcel,
      importName: "",
      loading: false,
      data: [],
      columns: [
        {
          title: "序号",
          width: 70,
          type: "index",
          align: "center"
        },
        {
          title: "食材编码",
          key: "materialId",
          align: "center",
          width: 150
        },
        {
          title: "食材种类",
          key: "foodClass",
          align: "center",
          width: 150
        },
        {
          title: "食材名称",
          key: "materialName",
          align: "center",
          width: 150
        },
        {
          title: "计量单位",
          key: "packagingUtil",
          align: "center",
          width: 150
        },
        {
          title: "价格",
          key: "packagingPrice",
          align: "center",
          width: 110
        },
        {
          title: "常用状态",
          slot: "materialStatus",
          align: "center",
          width: 100
        },
        {
          title: "供应商",
          key: "supplyName",
          align: "center",
          width: 150
        },
        {
          title: "称重入库",
          slot: "weightFlag",
          align: "center",
          width: 100
        },
        {
          title: "新增食材",
          slot: "isSystemFood",
          align: "center",
          width: 100
        },
        {
          title: "保质期/天",
          key: "shelfLifeHour",
          align: "center",
          width: 100
        },
        {
          title: "库存预警",
          key: "stockWarningPackagingQty",
          align: "center",
          width: 100
        },
        {
          title: "营养匹配",
          slot: "foodNutritionalStatus",
          align: "center",
          width: 100
        },
        {
          title: "营养标准",
          key: "nutritionalName",
          align: "center",
          width: 200
        },
        {
          title: "产地",
          key: "province",
          align: "center",
          width: 158
        },
        {
          title: "季节",
          key: "month",
          align: "center",
          width: 158
        },
        {
          title: "操作",
          width: 200,
          fixed: "right",
          slot: "operation",
          align: "center"
        }
      ],
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      },
      showTemp: true,
      countDown: "5分00秒",
      disabledCount: false,
      timer: null
    };
  },
  mounted() {
    this.materialTypeApi();
    this.onInit();
  },
  methods: {
    syncOrganLocalFoodApi() {
      this.disabledCount = true;
      this.syncInf();
      syncOrganLocalFood().then(res => {
        if(res.retCode == 2000) {
          this.$Message.success('同步成功')
        }
      
      });
    },
    //同步数据
    syncInf() {
      this.countDown = "5分00秒";
      let min = 5;
      let second1 = 0;
      let second2 = 0;
      this.timer = setInterval(() => {
        if (second2 > 0) {
          second2 = second2 - 1;
        } else {
          if (second1 > 0) {
            second1 = second1 - 1;
            second2 = 9;
          } else {
            if (min > 0) {
              min = min - 1;
              second1 = 5;
              second2 = 9;
            } else {
              this.disabledCount = false;
              clearInterval(this.timer);
            }
          }
        }
        this.countDown = `${min}分${second1}${second2}秒`;
      }, 1000);
    },
    // 初始化
    onInit() {
      this.localFoodSearchApi();
    },
    // 重置搜索
    reset() {
      this.$refs["formValidate"].resetFields();
      this.onInit();
    },
    // 导入错误
    onError(data) {
      if (data.retCode == 2888) {
        let content = "";
        data.data.map(it => {
          content += `<p style="margin-top:5px">${it}</p>`;
        });
        this.$Modal.warning({
          title: data.retMsg,
          content: content,
          width: "600",
          okText: "确认"
        });
      }
    },
    // 导出
    onExport() {
      this.exportLocalFoodVoExcelApi();
    },
    // 添加
    onAdd() {
      this.$refs.addFoodModal.show();
    },
    // 食谱原料绑定商品
    onBind() {
      this.$refs.bindFoodModal.show();
    },
    // 删除
    onDelete(row) {
      this.localFoodDeleteApi(row);
    },
    // 导入
    onImport(type) {
      if (type == 1) {
        this.importName = "导入食材";
        this.exportNutritionTagTemp = downloadLocalFoodExcelTemplate;
        this.uploadNutritionTag = inportLocalFoodVoExcel;
        this.showTemp = true;
      } else if (type == 2) {
        this.importName = "导入副食筹原料";
        this.uploadNutritionTag = inportRaiseFoodExcel;
        this.showTemp = false;
      } else {
        this.importName = "导入食材别名";
        this.exportNutritionTagTemp = downloadFoodAliasExcel;
        this.uploadNutritionTag = inportFoodAliasExcel;
        this.showTemp = true;
      }
      this.$refs["cusUploadNutritionTagModal"].show();
    },
    // 营养详情
    onDetail(item) {
      this.$refs["nutritionalDetails"].form.materialName = item.materialName;
      this.$refs["nutritionalDetails"].form.materialId = item.materialId;
      this.$refs["nutritionalDetails"].show();
    },
    // 营养匹配
    onPipei(item) {
      this.$refs.nutritionalMatching.form = item;
      this.$refs.nutritionalMatching.form.searchMaterialName = this.$cu.deepClone(
        item.materialName
      );
      this.$refs.nutritionalMatching.selectItem = item;

      this.$refs.nutritionalMatching.show();
    },
    // 编辑
    onEdit(row) {
      console.log('row',row);
      this.$refs.addFoodModal.form = this.$cu.deepClone(row);
      this.$refs.addFoodModal.form.weightFlag =
        this.$refs.addFoodModal.form.weightFlag + "";
      this.$refs.addFoodModal.form.materialStatus =
        this.$refs.addFoodModal.form.materialStatus + "";
      this.$refs.addFoodModal.show();
    },
    // 是否常用状态
    ifSwitchChange(row, index) {
      this.form.materialId = row.materialId;
      this.postBasicUpdateLocalFoodIsCommonlyApi(index);
    },
    // 获取食材清单列表
    localFoodSearchApi() {
      this.loading = true;
      return new Promise(resolve => {
        localFoodSearch({
          materialName: this.form.materialName, // 食材名称
          month: this.form.month, // 季节
          foodClass: this.form.foodClass, // 食材种类
          province: this.form.province, // 产地
          materialStatus: this.form.materialStatus, // 常用状态
          isSystemFood: this.form.isSystemFood, // 新增食材
          foodNutritionalStatus: this.form.foodNutritionalStatus, // 营养匹配
          current: this.pages.page,
          size: this.pages.pageSize
        }).then(res => {
          this.loading = false;
          if (res.retCode === 2000) {
            // res.data.forEach(element => {
            //     element.materialStatus = element.materialStatus === 1 ? true : false;
            // });
            this.data = res.data;
            this.pages.pageTotal = res.total;
            resolve();
          }
        });
      });
    },
    // 获取食材种类
    materialTypeApi() {
      return new Promise(resolve => {
        materialType({}).then(res => {
          if (res.retCode === 2000) {
            this.materialTypeList = res.data;
            resolve();
          }
        });
      });
    },
    // 删除食材
    localFoodDeleteApi(row) {
      return new Promise(resolve => {
        localFoodDelete({
          materialId: row.materialId
        }).then(res => {
          if (res.retCode === 2000) {
            this.$Message.success("删除成功");
            this.onInit();
            resolve();
          }
        });
      });
    },
    // 导出食材清单接口
    exportLocalFoodVoExcelApi() {
      this.$cu.showLoading();
      return new Promise(resolve => {
        exportLocalFoodVoExcel({
          materialName: this.form.materialName, // 食材名称
          month: this.form.month, // 季节
          foodClass: this.form.foodClass, // 食材种类
          province: this.form.province, // 产地
          materialStatus: this.form.materialStatus, // 常用状态
          isSystemFood: this.form.isSystemFood, // 新增食材
          foodNutritionalStatus: this.form.foodNutritionalStatus // 营养匹配
        }).then(res => {
          this.$cu.hideLoading(1);
          this.$Message.success("食材清单导出成功.");
          let blob = new Blob([res], { type: `application/vnd.ms-excel` });
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = "食材清单列表";
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(href);
          resolve();
        });
      });
    },
    // 是否常用状态更新-------------------接口
    postBasicUpdateLocalFoodIsCommonlyApi(index) {
      return new Promise(resolve => {
        let params = {
          materialId: this.form.materialId
        };
        postBasicUpdateLocalFoodIsCommonly(params).then(res => {
          if (res.retCode == 2000) {
            this.localFoodSearchApi();
            resolve();
          } else {
            setTimeout(() => {
              this.localFoodSearchApi();
            }, 30);
          }
        });
      });
    }
  },
  destroyed() {
    clearInterval(this.timer);
    window.removeEventListener("resize", this.resizeHandle, true);
  }
};
</script>
<style lang="less" scoped>
/deep/.ivu-input-icon {
  height: 40px !important;
  line-height: 40px !important;
}

/deep/.ivu-form-item  {
  margin-bottom: 20px;
}

/deep/.ivu-select-multiple .ivu-select-selection .ivu-select-placeholder {
  /* height: 40px !important; */
  line-height: 32px !important;
}
.content {
  height: 100%;
  // padding: 20px;
  &-bottom {
    background: #fff;
    border-radius: 6px;
    box-shadow: 1px 1px 2px 0px rgba(153, 182, 199, 0.2);
    padding: 20px;
  }
}

.formBox {
  width: 100%;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0px 4px 8px 0px rgba(108, 137, 165, 0.18);
  padding: 20px 20px 1px;
  display: flex;
  flex-wrap: wrap;

  &-item {
    margin-right: 48px;
  }
}

.mr_20 {
  margin-right: 20px;
}

.btnBox {
  width: 100%;
  display: flex;
  justify-content: space-between;
  // margin-bottom: 10px;

  div {
    display: flex;
  }
}
</style>
